package services

import (
	"govue3/db"
	"govue3/models"
	"govue3/utils"
	"strconv"
	"time"
)

type UserService interface {
	GetUserByID(id uint) (*models.User, error)
	UpdateUser(user *models.User) (*models.User, error)
	DeleteUser(id uint) error
}

type userService struct {
	sharding *db.Sharding
	cache    *utils.Cache
}

func NewUserService(sharding *db.Sharding, cache *utils.Cache) UserService {
	return &userService{
		sharding: sharding,
		cache:    cache,
	}
}

// GetUserByID 根据用户 ID 获取用户信息
func (s *userService) GetUserByID(id uint) (*models.User, error) {
	// 先从缓存获取
	cacheKey := "user:" + strconv.Itoa(int(id))
	if val, ok := s.cache.Get(cacheKey); ok {
		user := &models.User{}
		if err := user.UnmarshalBinary([]byte(val)); err == nil {
			return user, nil
		}
	}

	// 缓存未命中，从数据库获取
	db := s.sharding.GetDB(strconv.Itoa(int(id))) // 根据用户 ID 分片
	var user models.User
	if err := db.First(&user, id).Error; err != nil {
		return nil, err
	}

	// 将数据写入缓存
	if userData, err := user.MarshalBinary(); err == nil {
		s.cache.Set(cacheKey, string(userData), 5*time.Minute)
	}

	return &user, nil
}

// UpdateUser 更新用户信息
func (s *userService) UpdateUser(user *models.User) (*models.User, error) {
	// 更新数据库
	db := s.sharding.GetDB(strconv.Itoa(int(user.ID))) // 根据用户 ID 分片
	if err := db.Save(user).Error; err != nil {
		return nil, err
	}

	// 更新缓存
	cacheKey := "user:" + strconv.Itoa(int(user.ID))
	if userData, err := user.MarshalBinary(); err == nil {
		s.cache.Set(cacheKey, string(userData), 5*time.Minute)
	}

	return user, nil
}

// DeleteUser 删除用户信息
func (s *userService) DeleteUser(id uint) error {
	// 删除数据库记录
	db := s.sharding.GetDB(strconv.Itoa(int(id))) // 根据用户 ID 分片
	if err := db.Delete(&models.User{}, id).Error; err != nil {
		return err
	}

	// 删除缓存
	cacheKey := "user:" + strconv.Itoa(int(id))
	s.cache.Set(cacheKey, "", 0) // 设置 TTL 为 0，表示删除

	return nil
}
